<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>netty的基本使用，基本原理分析，相关问题解(更新中...) | 飞の博客</title><meta name="author" content="Fei"><meta name="copyright" content="Fei"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="netty的基本使用，基本原理分析，相关问题解（更新中）">
<meta property="og:type" content="article">
<meta property="og:title" content="netty的基本使用，基本原理分析，相关问题解(更新中...)">
<meta property="og:url" content="https://tengfei2233.gitee.io/2023/11/21/netty%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8%EF%BC%8C%E5%9F%BA%E6%9C%AC%E5%8E%9F%E7%90%86%E5%88%86%E6%9E%90%EF%BC%8C%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3-%E6%9B%B4%E6%96%B0%E4%B8%AD/index.html">
<meta property="og:site_name" content="飞の博客">
<meta property="og:description" content="netty的基本使用，基本原理分析，相关问题解（更新中）">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-11-10/netty-ai.png">
<meta property="article:published_time" content="2023-11-21T09:27:51.000Z">
<meta property="article:modified_time" content="2023-11-21T09:27:51.000Z">
<meta property="article:author" content="Fei">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="SpringBoot">
<meta property="article:tag" content="netty">
<meta property="article:tag" content="Socket">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-11-10/netty-ai.png"><link rel="shortcut icon" href="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/icon.png"><link rel="canonical" href="https://tengfei2233.gitee.io/2023/11/21/netty%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8%EF%BC%8C%E5%9F%BA%E6%9C%AC%E5%8E%9F%E7%90%86%E5%88%86%E6%9E%90%EF%BC%8C%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3-%E6%9B%B4%E6%96%B0%E4%B8%AD/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="msvalidate.01" content="2ADFA30867CBC6E090E3C5B244DC311D"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/6.3.0/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.staticfile.org/fancyapps-ui/4.0.31/fancybox.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?07a1f58fb95d3d4a97c2ae0a181c9964";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.staticfile.org/flickr-justified-gallery/2.1.2/fjGallery.min.js',
      css: 'https://cdn.staticfile.org/flickr-justified-gallery/2.1.2/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'netty的基本使用，基本原理分析，相关问题解(更新中...)',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-11-21 17:27:51'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/fei.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">24</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" target="_blank" rel="noopener" href="https://github.com/tengfei2233"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-11-10/netty-ai.png')"><nav id="nav"><span id="blog-info"><a href="/" title="飞の博客"><span class="site-name">飞の博客</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" target="_blank" rel="noopener" href="https://github.com/tengfei2233"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">netty的基本使用，基本原理分析，相关问题解(更新中...)</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-11-21T09:27:51.000Z" title="发表于 2023-11-21 17:27:51">2023-11-21</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-11-21T09:27:51.000Z" title="更新于 2023-11-21 17:27:51">2023-11-21</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java/">Java</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java/SpringBoot/">SpringBoot</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>23分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="netty的基本使用，基本原理分析，相关问题解(更新中...)"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="netty的基本使用，基本原理分析，相关问题解决-更新中…"><a href="#netty的基本使用，基本原理分析，相关问题解决-更新中…" class="headerlink" title="netty的基本使用，基本原理分析，相关问题解决(更新中…)"></a>netty的基本使用，基本原理分析，相关问题解决(更新中…)</h2><p>[TOC]</p>
<h3 id="netty的基本介绍"><a href="#netty的基本介绍" class="headerlink" title="netty的基本介绍"></a>netty的基本介绍</h3><h4 id="什么是netty"><a href="#什么是netty" class="headerlink" title="什么是netty"></a>什么是netty</h4><blockquote>
<p>引用<a target="_blank" rel="noopener" href="https://netty.io/">netty官网</a>的一句话：Netty是一个NIO客户端服务器框架，可以快速轻松地开发网络应用程序，如协议服务器和客户端。它极大地简化了TCP和UDP套接字服务器等网络编程。 “快速和简单”并不意味着最终的应用程序将遭受可维护性或性能问题。Netty是根据实现许多协议(如FTP、SMTP、HTTP和各种基于二进制和文本的遗留协议)所获得的经验精心设计的。因此，Netty成功地找到了一种方法，在不妥协的情况下实现易于开发、性能、稳定性和灵活性。</p>
<p>简单来说，netty就是Java领域的一个网络通信标杆级框架，大量框架底层网络通信依赖netty，像zookeeper，dubbo，elasticsearch，redisson等。</p>
<p>netty底层是对Java原生NIO的高度封装，提供更简单的API，使NIO程序的开发不用那么复杂，且自定义ByteBuf数据类型，对标Java原生的ByteBuffer，实现了数据的零拷贝，数据传输效率也更高。</p>
</blockquote>
<h4 id="netty与tomcat的区别是什么"><a href="#netty与tomcat的区别是什么" class="headerlink" title="netty与tomcat的区别是什么"></a>netty与tomcat的区别是什么</h4><blockquote>
<p>netty是一个网络通信框架，可以自定义多种协议，不仅仅是http协议，也可以是ftp协议，websocke协议等，也可以自定义协议，自定义程度非常高，性能也很高。</p>
<p>tomcat是一个web容器，符合servlet容器标准，是对http协议的高度封装，针对http协议有着特定的优化，因此tomcat支持特定协议领域的网络通信框架。</p>
<p>**举个简单的例子：**有两个厨师，A厨师什么菜都会做，但是需要你告诉他做什么，帮他买好菜；B厨师只会做红烧肉，但他什么都不需要你干，不用指挥，他就能把菜做好。因此A厨师就像netty，B厨师tomcat。</p>
</blockquote>
<h4 id="相关概念-x2F-问题"><a href="#相关概念-x2F-问题" class="headerlink" title="相关概念&#x2F;问题"></a>相关概念&#x2F;问题</h4><ul>
<li>什么是BIO，NIO，AIO</li>
</ul>
<blockquote>
<p>BIO：BIO是阻塞IO，就是一个网络请求进来，就要给这个连接分配一个线程，这个线程只为这个连接服务，如果这个连接没有数据传输，这个线程就一只阻塞在这里。**举个例子：**你去订蛋糕，在蛋糕没好之前，你一直在蛋糕店里面守着，期间你无法去干啥，这段事件就浪费了，你也就被阻塞了。</p>
<p>NIO：NIO是同步非阻塞IO，就是一个网络请求进来，我不需要给他分配一个线程，而是将这个连接加入到一个容器中，这个线程不断去轮询，检测某个请求是否有消息发送过来了，如果有，我就将它放入另一个线程就行处理，同时往下轮询检查其它的连接。**举个例子：**你去订蛋糕，下订单后，你去附近的商场逛街，隔一段时间你就打一个电话过去，蛋糕好了没有，等有个电话打过去刚好蛋糕做好了，你就可以回去拿了。</p>
<p>AIO：AIO就是异步非阻塞IO，就是一个网络请求进来，我不需要给他分配一个线程，而是将这个连接加入一个容器中，也不用线程去轮询，而是等如果其中一个连接有消息进来，它主动通知我，我再将这个连接的消息交给一个线程来处理。**举个例子：**你去订蛋糕，下订单后，你去附近的商城逛街，也不用打电话过去，等蛋糕做好了，店家主动打电话告诉你，你再去拿蛋糕。</p>
<p>所以说，店家为什么不能主动送过来呢😂</p>
<p>以上例子只是一些简单的抽象，比如线程可以池化设计，一个线程可以管理一部分连接等。</p>
</blockquote>
<ul>
<li>什么是网络通信</li>
</ul>
<blockquote>
<p>什么是网络通信呢，就是不同计算机间通过网络数据流进行数据交换，目前都是基于传输层TCP&#x2F;UPD两大协议。</p>
</blockquote>
<ul>
<li>什么是零拷贝</li>
</ul>
<blockquote>
<p>零拷贝不是说不需要进行数据拷贝了，只是减少数据拷贝次数，同时减少CPU上下文切换次数，这样无疑能提高数据传输的效率。</p>
<p>传统的数据从硬盘拷贝到网卡</p>
<ul>
<li>数据从硬盘读取到系统内核read buffer缓冲区（一次拷贝）</li>
<li>数据从内核的read buffer缓冲区拷贝到用户缓冲区（两次拷贝）</li>
<li>数据从用户缓存区拷贝到内核的socket buffer缓冲区（三次拷贝）</li>
<li>数据从socket buffer缓冲区拷贝到网卡接口（四次拷贝）</li>
<li>期间CPU发生了两次上下文切换，一次切换是第二次拷贝时：内核态到用户态，二次切换是第三次拷贝时：用户态到内核态</li>
</ul>
<p>零拷贝将数据从硬盘拷贝到网卡</p>
<ul>
<li>硬盘文件由DMA从硬盘拷贝到内核read buffer缓冲区（一次拷贝）</li>
<li>DMA将内核read buffer缓冲区数据拷贝到网卡接口（两次拷贝）</li>
</ul>
<p>零拷贝相比于传统的拷贝，少了两次数据拷贝和两次CPU上下文切换，效率提升非常多。</p>
<p>DMA：DMA（Direct Memory Access，直接内存访问）是一种计算机系统中的技术，用于实现数据在主存和外设之间的直接传输，而无需通过中央处理器（CPU）的干预。DMA 可以提高数据传输的效率，减少 CPU 的负载，同时也有助于实现零拷贝技术。同时DMA技术是需要有硬件支持的，一般现代主板都集成有DMA处理芯片。</p>
</blockquote>
<h3 id="netty的基本使用（Socket连接）"><a href="#netty的基本使用（Socket连接）" class="headerlink" title="netty的基本使用（Socket连接）"></a>netty的基本使用（Socket连接）</h3><p><font color="red">以下netty的使用都是基于netty4</font></p>
<h4 id="netty服务端"><a href="#netty服务端" class="headerlink" title="netty服务端"></a>netty服务端</h4><ul>
<li>创建maven项目</li>
<li>引入依赖</li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>io.netty<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>netty-all<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.1.94.Final<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>NettyServer（服务端）</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">NettyServer</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">NioEventLoopGroup</span> <span class="variable">boss</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>();</span><br><span class="line">        <span class="type">NioEventLoopGroup</span> <span class="variable">worker</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">ServerBootstrap</span> <span class="variable">serverBootstrap</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ServerBootstrap</span>();</span><br><span class="line">            serverBootstrap.group(boss, worker)</span><br><span class="line">                    .channel(NioServerSocketChannel.class)</span><br><span class="line">                    .handler(<span class="keyword">new</span> <span class="title class_">LoggingHandler</span>(LogLevel.INFO))</span><br><span class="line">                    .option(ChannelOption.SO_BACKLOG, <span class="number">1024</span>)</span><br><span class="line">                    .childOption(ChannelOption.SO_KEEPALIVE, <span class="literal">true</span>)</span><br><span class="line">                    .childHandler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;SocketChannel&gt;() &#123;</span><br><span class="line">                        <span class="meta">@Override</span></span><br><span class="line">                        <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(SocketChannel ch)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">                            ch.pipeline()</span><br><span class="line">                                    .addLast(<span class="keyword">new</span> <span class="title class_">InServerChannelHandler</span>());</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;);</span><br><span class="line">			<span class="comment">// 绑定9909端口</span></span><br><span class="line">            <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> serverBootstrap.bind(<span class="number">9909</span>).sync().channel();</span><br><span class="line">            System.out.println(<span class="string">&quot;---------------服务端启动，端口：&quot;</span> + <span class="number">9909</span> + <span class="string">&quot;---------------&quot;</span>);</span><br><span class="line">            channel.closeFuture().sync();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(e);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="comment">// 关闭线程组</span></span><br><span class="line">            boss.shutdownGracefully();</span><br><span class="line">            worker.shutdownGracefully();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>InServerChannelHandler（自定义服务端入站处理器）</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">InServerChannelHandler</span> <span class="keyword">extends</span> <span class="title class_">ChannelInboundHandlerAdapter</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelActive</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;---------服务端连接成功----------&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">// 时间</span></span><br><span class="line">        <span class="type">LocalDateTime</span> <span class="variable">now</span> <span class="operator">=</span> LocalDateTime.now();</span><br><span class="line">        <span class="type">DateTimeFormatter</span> <span class="variable">formatter</span> <span class="operator">=</span> DateTimeFormatter.ofPattern(<span class="string">&quot;yyyy-MM-dd HH:mm:ss.SSS&quot;</span>);</span><br><span class="line">        <span class="type">String</span> <span class="variable">formattedDateTime</span> <span class="operator">=</span> now.format(formatter);</span><br><span class="line">        <span class="type">ByteBuf</span> <span class="variable">buff</span> <span class="operator">=</span> (ByteBuf) msg;</span><br><span class="line">        <span class="type">String</span> <span class="variable">strMsg</span> <span class="operator">=</span> buff.toString(CharsetUtil.UTF_8);</span><br><span class="line">        System.out.println(<span class="string">&quot;---------服务端收到数据[&quot;</span> + formattedDateTime + <span class="string">&quot;]：&quot;</span> + strMsg + <span class="string">&quot;-----------&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>运行main方法启动netty服务端，监听9909端口</li>
</ul>
<h4 id="netty客户端"><a href="#netty客户端" class="headerlink" title="netty客户端"></a>netty客户端</h4><ul>
<li>创建maven项目</li>
<li>引入依赖</li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>io.netty<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>netty-all<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.1.94.Final<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>ClientServer（客户端），通过ip与port监听服务端</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">NettyClient</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">NioEventLoopGroup</span> <span class="variable">worker</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">NioEventLoopGroup</span>();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">Bootstrap</span> <span class="variable">bootstrap</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Bootstrap</span>();</span><br><span class="line">            bootstrap.group(worker)</span><br><span class="line">                    .channel(NioSocketChannel.class)</span><br><span class="line">                    .option(ChannelOption.TCP_NODELAY, <span class="literal">true</span>)</span><br><span class="line">                    .handler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;SocketChannel&gt;() &#123;</span><br><span class="line">                        <span class="meta">@Override</span></span><br><span class="line">                        <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(SocketChannel ch)</span> &#123;</span><br><span class="line">                            ch.pipeline()</span><br><span class="line">                                    .addLast(<span class="keyword">new</span> <span class="title class_">ClientChannelHandel</span>());</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;);</span><br><span class="line"></span><br><span class="line">            <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> bootstrap.connect(<span class="string">&quot;localhost&quot;</span>, <span class="number">9909</span>).sync().channel();</span><br><span class="line">            <span class="comment">// 可以在这里进行其他操作，如发送数据</span></span><br><span class="line"></span><br><span class="line">            channel.closeFuture().sync();</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            worker.shutdownGracefully();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>ClientChannelHandel（自定义客户端入站处理器）</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">ClientChannelHandel</span> <span class="keyword">extends</span> <span class="title class_">ChannelInboundHandlerAdapter</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;客户端收到数据：&quot;</span> + msg.toString(CharsetUtil.UTF_8)));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelActive</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;---------客户端进行连接----------&quot;</span>);</span><br><span class="line">        <span class="comment">// 向服务端发送消息</span></span><br><span class="line">        ctx.channel().writeAndFlush(Unpooled.copiedBuffer(<span class="string">&quot;你好，我是netty客户端&quot;</span>, CharsetUtil.UTF_8));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>启动客户端，连接到客户端，便可以发送第一条消息：你好，我是netty客户端</li>
</ul>
<h3 id="基本代码分析"><a href="#基本代码分析" class="headerlink" title="基本代码分析"></a>基本代码分析</h3><h4 id="服务端"><a href="#服务端" class="headerlink" title="服务端"></a>服务端</h4><ul>
<li>NioEventLoopGroup类</li>
</ul>
<blockquote>
<p>NioEventLoopGroup底层是一个线程池，线程池中线程数量为机器逻辑处理器数量*2，其中使用了两个线程组，一个boss线程组和一个woker工作线程组。</p>
<p>**逻辑处理器：**对于没有超线程的处理器，逻辑处理器就是物理核心的数量，对于有超线程的处理器，逻辑处理器就是超线程的数量</p>
<p>**为什么要使用两个线程组：**boss线程组用于请求的连接和服务端端口的监听，worker线程组用于入站消息的接收，解码，出站消息的编码，发送。因此可以得出，boss线程的压力要小很多，所以boss线程池的线程数量可以设置小一些。NioEventLoopGroup构造器的一个int入参就是设置线程池中线程的数量的。</p>
</blockquote>
<ul>
<li>ServerBootstrap与Bootstrap类</li>
</ul>
<blockquote>
<p>**ServerBootstrap：**ServerBootstrap用于netty服务端，请求的连接，数据的入站出站处理。</p>
<p>**Bootstrap：**Bootstrap用于netty客户端，因为不需要处理连接请求，因此只需要一个worker线程组设置就行。</p>
</blockquote>
<ul>
<li>channel()方法</li>
</ul>
<blockquote>
<p>用于设置Netty底层数据IO类型，NioServerSocketChannel指的是服务端使用NIO类型，也可以指定OioServerSocketChannel，指的是BIO，不过有NIO了，基本上也不用BIO了；也可以设置EpollServerSocketChannel，指的是Linux系统下的epoll IO模型，不过epoll存在空轮询问题，会导致CPU资源空消耗，所以此处推荐NioServerSocketChannel用于服务端，NioSocketChannel用于客户端。</p>
</blockquote>
<ul>
<li>handler()方法</li>
</ul>
<blockquote>
<p>一般是设置整个服务的一些处理器，上面代码<code>handler(new LoggingHandler(LogLevel.INFO))</code>，用于设置netty日志处理的级别，这个handler()方法也基本上很少用</p>
</blockquote>
<ul>
<li>option()</li>
</ul>
<blockquote>
<p>一般用于设置整个服务的一些参数，向<code>option(ChannelOption.SO_BACKLOG, 1024)</code>，用于设置连接等待队列的大小，也可以设置一些其它参数，例如是否启动：TCP_NODELAY，启用或禁用 Nagle’s algorithm。这是一种改善网络效率的算法，通过减少小包的数量来优化网络。</p>
</blockquote>
<ul>
<li>childOption()方法</li>
</ul>
<blockquote>
<p>childOption的用法与option基本上类似，只不过是针对连接来设定的，不过基本上功能也和option类似。</p>
</blockquote>
<ul>
<li><font color="red">childHandler()方法，重要</font></li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">.childHandler(<span class="keyword">new</span> <span class="title class_">ChannelInitializer</span>&lt;SocketChannel&gt;() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">initChannel</span><span class="params">(SocketChannel ch)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        ch.pipeline()</span><br><span class="line">            .addLast(<span class="keyword">new</span> <span class="title class_">InServerChannelHandler</span>());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<blockquote>
<p>入参为：实现ChannelInitializer匿名内部类，泛型参数为SocketChannel，接收每一个连接发送的消息，向每一个连接发送消息，都要经过ch.pipline下的处理器，使用了责任链模式，以addLast为例，就是在最后添加InServerChannelHandler自定义处理器。</p>
<p><strong>责任链模式：</strong> 处理逻辑像链条一样连接在一起，上游处理完毕将结果传递给下游处理器，下游处理器开始执行。</p>
<p><strong>pipeline()中处理器链添加的位置：</strong>（如果未指定处理器，处理器链上默认是没有处理器的）</p>
<ul>
<li><code>addFirst()</code>: 将指定的处理器添加到处理器链的开头位置。</li>
<li><code>addLast()</code>：将指定的处理器添加到处理器链的结束位置。</li>
<li><code>addBefore()</code>: 在指定的处理器之前添加一个新的处理器。</li>
<li><code>addAfter()</code>: 在指定的处理器之后添加一个新的处理器。</li>
<li><code>replace()</code>: 替换指定名称的处理器为一个新的处理器。</li>
</ul>
<p>不管按什么方式添加处理器，入站信息都是从处理器链头部往尾部执行的，而出站信息则是从处理器链尾部往头部执行的。</p>
</blockquote>
<ul>
<li>入站信息&#x2F;入站处理器</li>
</ul>
<blockquote>
<p>以服务端为例，入站信息就是客户端发给服务端的数据，也叫服务端接收的消息；而入站处理器就是用来处理这些消息的，比如对这些消息进行解密，编码，转格式等。</p>
<p>常见入站处理器：StringDecoder（字符串解码，将ByteBuf等格式转化成String格式）。</p>
<p>入站处理器默认都是都是继承ChannelInboundHandlerAdapter，在此基础上自定义自己的需求</p>
</blockquote>
<p><img src="https://hexo-images-fei.oss-cn-hangzhou.aliyuncs.com/images/1694080326-image-20230907175206141.png" alt="image-20230907175206141"></p>
<ul>
<li>出站信息&#x2F;出站处理器</li>
</ul>
<blockquote>
<p>以服务端为例，出站信息就是服务端发给客户端的数据，也叫服务端发送数据；而出站处理器就是用来对要发出去的数据进行一系列处理，像转格式，加密等。</p>
<p>常见出站处理器：StringEncoder（字符串编码，将String格式转化成ByteBuf格式）</p>
<p>出站处理器默认都是继承ChannelOutboundHandlerAdapter，在此基础上自定义自己的需求</p>
</blockquote>
<p><img src="https://hexo-images-fei.oss-cn-hangzhou.aliyuncs.com/images/1694080344-image-20230907175224432.png" alt="image-20230907175224432"></p>
<ul>
<li>双工处理器</li>
</ul>
<blockquote>
<p>基本上这种是既可以处理入站数据，也可以处理出站数据，双工处理器一般是继承一个入站处理器类和实现一个出站处理器接口，或者继承一个出站处理器类和实现入站处理器接口。</p>
</blockquote>
<p><strong>总的来说，netty的数据处理器链上只有入站处理器和出站处理器两种类型，其它都是在此基础上封装而来的。</strong></p>
<h4 id="入站处理器"><a href="#入站处理器" class="headerlink" title="入站处理器"></a>入站处理器</h4><p>以最开始的服务端代码为例，创建InServerChannelHandler类，继承ChannelInboundHandlerAdapter，重写父类的方法，其中重写的一系列方法就是消息入站时一系列生命周期的回调，包括连接时回调，异常时回调，接收消息时回调等，以下列举各个回调的作用。</p>
<p>在描述以下方法前，先说下每个方法都会有的一个入参，<strong>ChannelHandlerContext</strong>，表示当前连接管道的上下文环境，一般是使用<code>ctx.channel</code>获取当前连接管道，一个连接就时一个channel，可以通过channel向连接的这个客户端发送信息，获取当前客户端的连接id，地址等信息。</p>
<ul>
<li><strong><code>channelRegistered(ChannelHandlerContext ctx)</code></strong></li>
</ul>
<blockquote>
<p>连接注册到EventLoop，就是连接已经到达了连接处理线程</p>
</blockquote>
<ul>
<li><strong><code>channelUnregistered(ChannelHandlerContext ctx)</code></strong></li>
</ul>
<blockquote>
<p>连接从EventLoop上取消注册，连接离开了连接处理线程</p>
</blockquote>
<ul>
<li><strong><code>channelActive(ChannelHandlerContext ctx)</code></strong></li>
</ul>
<blockquote>
<p>连接成功时调用该方法，表示一个请求已经连接成功，在这里一般做一些初始化的工作，比如将连接加入到容器中，下次要用的时候直接根据id从容器中取出该channel，向该channel发送消息，可用于客户端间的互相通信</p>
</blockquote>
<ul>
<li><strong><code>channelInactive(ChannelHandlerContext ctx)</code></strong></li>
</ul>
<blockquote>
<p>连接已断开，这里是指连接主动断开了，如果因关闭程序断开，则不会运行这个回调，而是抛异常回调</p>
</blockquote>
<ul>
<li><strong><code>channelRead(ChannelHandlerContext ctx, Object msg)</code></strong></li>
</ul>
<blockquote>
<p>**最主要的方法：**接收客户端发来的数据，进行相关操作。</p>
<p>不加入其它内置的入站处理器的话，netty默认接收到的数据类型就是ByteBuf，这是netty自定义对标Java ByteBuffer的自定义字节缓冲区，ByteBuf只是一个抽象类，PooledByteBuf便是其上层实现，还有一种就是接收的不是文本，字节类数据，而是文件类数据，此时数据类型便是FileRegion类型，在使用Object msg，要对数据进行转换。</p>
<p>其实自带的入站处理器StringDecorder其实是将ByteBuf转成String类型。</p>
<p>使用ctx.channel().writeAndFlush()方法向channel所对应的客户端发送数据，在没有自定义出站处理器或者没有出站处理器时，writeAndFlush能就收的数据类型便只有ByteBuf或则FileRegion了，可以使用Unpooled类的方法将不同数据类型转成ByteBuf，以下是Unpooled类中方法的一些使用方式：</p>
<p>**Unpooled.buffer(int initialCapacity, int maxCapacity)<strong>：创建一个堆内存（Heap Buffer）ByteBuf，它将数据存储在JVM的堆空间中。这种类型的缓冲区，数据的读写都会通过一个中间数组进行，这可能会引入一些额外的内存复制操作。不过，由于可以利用JVM 的自动垃圾回收，堆内存的分配和释放通常比堆外内存更高效。</strong>Unpooled.directBuffer(int initialCapacity, int maxCapacity)**：创建一个直接内存（Direct Buffer）ByteBuf，它将数据存储在JVM堆空间之外的直接内存中。这种类型的缓冲区可以减少在与本地 <em>I&#x2F;O</em> 操作交互时的内存复制操作，从而提高性能。但是，直接内存的分配和释放通常比堆内存更昂贵，而且不受JVM垃圾回收的管理。<br>**Unpooled.wrappedBuffer(byte[] array)**：创建一个包装缓冲区（Wrapped Buffer）ByteBuf，它会将已有的字节数组或ByteBuffer 包装为 ByteBuf，而不会复制数据。如果修改ByteBuf中的数据，也会影响到原来的字节数组或ByteBuffer。<br>**Unpooled.copiedBuffer(byte[] array)**：创建一个复制缓冲区（Copied Buffer）ByteBuf，它会将已有的字节数组、字符串或ByteBuffer 等数据复制一份到ByteBuf中。如果修改ByteBuf 中的数据，不会影响到原来的数据。</p>
</blockquote>
<ul>
<li><strong><code>channelReadComplete(ChannelHandlerContext ctx)</code></strong></li>
</ul>
<blockquote>
<p>一般接收一次数据，此方法只调用一次，因为接收的数据可能过大，分几次读取完毕，在最后一次读取后调用。什么意思呢？就是客户端一次性向服务端发送大量数据，导致服入站缓冲区满了，无法一次性将数据读完，可能得分几次读完，那么这个方法就是在最后一次读完得时候调用，也就是一次接收只读一次。</p>
</blockquote>
<ul>
<li><strong><code>userEventTriggered(ChannelHandlerContext ctx, Object evt)</code></strong></li>
</ul>
<blockquote>
<p>触发用户自定义事件：什么叫用户自定义事件，就是该处理器的上游处理器在调用了fireUserEventTriggered方法，将调用链传递到这个处理器，（因为调用了fireUserEventTriggered方法，上游处理器变结束运行了），到了该处理器，就会触发userEventTriggered方法，通过判断传入的参数Object evt，判断是哪个处理器调用的，进行相关判断，执行相应的方法。</p>
<p>一般这个用户自定义事件搭配IdleStateHandler处理器可以实现心跳检测，下面将会介绍到如何实现心跳检测。</p>
</blockquote>
<ul>
<li><strong><code>channelWritabilityChanged(ChannelHandlerContext ctx)</code></strong></li>
</ul>
<blockquote>
<p>判断channel通道是不是可写状态：为什么会变的不可写呢，因为一次性向发送缓冲区写入太多的数据，或者写入速度超出了网络传输能力，导致缓存区过满就会导致变成不可写状态，不可写状态不代表就发送失败了，只是发送被阻塞了，等缓冲区不满了，又可以继续写入发送了这里的发送缓存区，是指服务端向客户端发送数据。</p>
</blockquote>
<ul>
<li><strong><code>exceptionCaught(ChannelHandlerContext ctx, Throwable cause)</code></strong></li>
</ul>
<blockquote>
<p>网络出错导致短连，数据解析错误等一系列错误，抛出的异常在此捕获</p>
</blockquote>
<h4 id="出站处理器"><a href="#出站处理器" class="headerlink" title="出站处理器"></a>出站处理器</h4><p>出站处理器与入站处理器相对应，出站处理器主要是对发往客户端的数据进行相关处理，创建OutServerChannelHandler类，继承ChannelOutboundHandlerAdapter，重写父类的方法，将出站处理器加入到pipline处理器链上，重写的父类方法便是数据发往客户端时的一些回调，以下对这些回调方法进行一些简要的介绍。由于自定义出站处理器用的远没有入站处理器那么频繁，所以以下只是对回调方法的一些简要的介绍。</p>
<ul>
<li><strong><code>bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise)</code></strong></li>
</ul>
<blockquote>
<p>出站缓冲区绑定到本地网卡，因为数据发送的过程是，数据先发往出站缓冲区，出站缓冲区再发往本地网卡，绑定本地网卡，说明出站缓存区的数据可以发往本地网卡了。</p>
</blockquote>
<ul>
<li><strong><code>connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise)</code></strong></li>
</ul>
<blockquote>
<p>绑定到远程网卡，也就是客户端网卡，两者间联通了，说明数据可以从本地网卡发往远程客户端网卡了</p>
</blockquote>
<ul>
<li><strong><code>disconnect(ChannelHandlerContext ctx, ChannelPromise promise)</code></strong></li>
</ul>
<blockquote>
<p>与客户端断开连接</p>
</blockquote>
<ul>
<li><strong><code>close(ChannelHandlerContext ctx, ChannelPromise promise)</code></strong></li>
</ul>
<blockquote>
<p>关闭连接通道</p>
</blockquote>
<ul>
<li><strong><code>deregister(ChannelHandlerContext ctx, ChannelPromise promise)</code></strong></li>
</ul>
<blockquote>
<p>将连接通道从EventLoop中移除</p>
</blockquote>
<ul>
<li><strong><code>read(ChannelHandlerContext ctx)</code></strong></li>
</ul>
<blockquote>
<p>这个read其实是从入站缓冲区读取数据出来，注意是入站缓冲区，个人也不晓得为什么要放在这里，与出站处理器有啥关系</p>
</blockquote>
<ul>
<li><strong><code>write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)</code></strong></li>
</ul>
<blockquote>
<p>出站处理器的核心回调方法：obj就是要发往客户端的数据，默认不处理是ByteBuf或FileRegion类型，可以手动在此处转类型，或者对数据进行加密等。</p>
</blockquote>
<ul>
<li><strong><code>flush(ChannelHandlerContext ctx)</code></strong></li>
</ul>
<blockquote>
<p>将出站缓冲区的数据写入到本地网卡中</p>
</blockquote>
<h3 id="心跳检测"><a href="#心跳检测" class="headerlink" title="心跳检测"></a>心跳检测</h3><blockquote>
<p>心跳检测其实就是客户端定时向服务端发送一个特定的数据，服务端对每次对其回应一个特定的数据，用来检测客户端与服务端之间是否还存活着；如果客户端发现向服务端发送数据不成功，则主动断开连接，同理，服务端也是类似。</p>
<p>netty心跳检测用到了IdleStateHandler这个处理器类，这个处理器就上面说的既是入站处理器又是出站处理器，以下是它的继承结构。首先继承ChannelDuplexHandler类；ChannelDuplexHandler类又继承ChannelInboundHandlerAdapter入站处理器类和ChannelOutboundHandler出站处理器接口。</p>
</blockquote>
<ul>
<li>IdleStateHandler继承结构</li>
</ul>
<p><img src="https://hexo-images-fei.oss-cn-hangzhou.aliyuncs.com/images/1694135382-image-20230908090942034.png" alt="image-20230908090942034"></p>
<ul>
<li>ChannelDuplexHandler继承结构</li>
</ul>
<p><img src="https://hexo-images-fei.oss-cn-hangzhou.aliyuncs.com/images/1694135443-image-20230908091043232.png" alt="image-20230908091043232"></p>
<ul>
<li>以下对IdleStateHandler处理器的基本入参做一个介绍</li>
</ul>
<blockquote>
<p>**<code>readerIdleTime</code>**：代表几秒内没有收到数据就触发下游处理器用户事件回调userEventTriggered，比如你需要5秒内没有数据读取就触发下游处理器userEventTriggered事件，0代表禁用按读取数据判断。一般用在服务端，因为服务端主要接收客户端心跳包数据。</p>
<p>**<code>writerIdleTime</code>**：代表写入数据流的判断，几秒没有写入数据流就向触发下游用户自定义事件。0代表禁用。一般用在客户端，客户端主要是向服务端发送心跳数据。</p>
<p>**<code>allIdleTime</code>**：代表的是有数据，不管是写入还是读取，只要有数据就行。0代表禁用。</p>
<p>默认时间单位为秒。</p>
</blockquote>
<h4 id="服务端处理"><a href="#服务端处理" class="headerlink" title="服务端处理"></a>服务端处理</h4><ul>
<li>在处理器链的自定义处理器链前面加上IdleStateHandler处理器</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 0表示禁用，10表示10s内没有接收到该channel的数据，就触发下游用户自定义事件</span></span><br><span class="line"><span class="comment">// 事件类型为IdleStateEvent</span></span><br><span class="line">addLast(<span class="keyword">new</span> <span class="title class_">IdleStateHandler</span>(<span class="number">10</span>, <span class="number">0</span>, <span class="number">0</span>, TimeUnit.SECONDS))</span><br></pre></td></tr></table></figure>

<ul>
<li>编写自定义处理器链的channelRead回调部分</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 添加在channelRead回调的代码最前方，反正是普通数据处理的前方</span></span><br><span class="line"><span class="comment">// 将数据转成ByteBuf</span></span><br><span class="line"><span class="type">ByteBuf</span> <span class="variable">buff</span> <span class="operator">=</span> (ByteBuf) msg;</span><br><span class="line"><span class="comment">// 转成string</span></span><br><span class="line"><span class="type">String</span> <span class="variable">strMsg</span> <span class="operator">=</span> buff.toString(CharsetUtil.UTF_8);</span><br><span class="line"><span class="comment">// 判断传过来的数据是否是ping，是的话就是客户端的心跳包</span></span><br><span class="line"><span class="keyword">if</span> (strMsg.equals(<span class="string">&quot;ping&quot;</span>)) &#123;</span><br><span class="line">    <span class="comment">// 我们就给客户端回应一个pong,表示收到了心跳</span></span><br><span class="line">    ctx.channel().writeAndFlush(Unpooled.copiedBuffer(<span class="string">&quot;pong&quot;</span>, CharsetUtil.UTF_8))</span><br><span class="line">        <span class="comment">// 这个是事件监听，表示发送失败直接关闭连接，发送失败基本上是连接不到客户端了</span></span><br><span class="line">        .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>编写自定义处理器链的userEventTriggered用户自定义事件部分</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 心跳检测，判断是否是IdleStateEvent事件</span></span><br><span class="line"><span class="keyword">if</span> (evt <span class="keyword">instanceof</span> IdleStateEvent) &#123;</span><br><span class="line">    <span class="type">IdleStateEvent</span> <span class="variable">e</span> <span class="operator">=</span> (IdleStateEvent) evt;</span><br><span class="line">    <span class="comment">// 判断是否是未读取事件</span></span><br><span class="line">    <span class="keyword">if</span> (e.state() == IdleState.READER_IDLE) &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;--------超时未读取--------&quot;</span>);</span><br><span class="line">        <span class="comment">// 未发送数据，代表对面可能特殊原因关闭连接了，这里我们也关闭连接</span></span><br><span class="line">        ctx.channel().close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 不是的话跳过</span></span><br><span class="line"><span class="built_in">super</span>.userEventTriggered(ctx, evt);</span><br></pre></td></tr></table></figure>

<h4 id="客户端处理"><a href="#客户端处理" class="headerlink" title="客户端处理"></a>客户端处理</h4><ul>
<li>在处理器链的自定义处理器链前面加上IdleStateHandler处理器</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 0表示禁用，6表示6s内没有向该channel写入数据，就触发下游用户自定义事件</span></span><br><span class="line"><span class="comment">// 事件类型为IdleStateEvent</span></span><br><span class="line">addLast(<span class="keyword">new</span> <span class="title class_">IdleStateHandler</span>(<span class="number">0</span>, <span class="number">6</span>, <span class="number">0</span>, TimeUnit.SECONDS))</span><br></pre></td></tr></table></figure>

<ul>
<li>编写自定义处理器链的userEventTriggered用户自定义事件部分</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 判断是否是IdleStateEvent事件</span></span><br><span class="line"><span class="keyword">if</span> (evt <span class="keyword">instanceof</span> IdleStateEvent) &#123;</span><br><span class="line">    <span class="type">IdleStateEvent</span> <span class="variable">event</span> <span class="operator">=</span> (IdleStateEvent) evt;</span><br><span class="line">    <span class="comment">// 是否是未写入事件</span></span><br><span class="line">    <span class="keyword">if</span> (event.state() == IdleState.WRITER_IDLE) &#123;</span><br><span class="line">        <span class="comment">// 向服务端发送ping数据</span></span><br><span class="line">        ctx.writeAndFlush(Unpooled.copiedBuffer(<span class="string">&quot;ping&quot;</span>, CharsetUtil.UTF_8))</span><br><span class="line">            <span class="comment">// 如果发送失败，直接关闭连接</span></span><br><span class="line">            .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 不是的话跳过</span></span><br><span class="line"><span class="built_in">super</span>.userEventTriggered(ctx, evt);</span><br></pre></td></tr></table></figure>

<ul>
<li>以上便是简易的心跳检测程序</li>
</ul>
<h4 id="进阶"><a href="#进阶" class="headerlink" title="进阶"></a>进阶</h4><blockquote>
<p>现在有这么一个场景，如果客户端与服务端之间发送的数据不止是String，可能还有文件，JSON等，或则哪天突然ping这个字符被当作普通字符使用了，那么服务端在接收到时就会将其按照心跳处理了。</p>
<p>所以这里涉及到了自定义数据解析类型，自定义数据传输格式的内容了，咱们以后有机会再说。</p>
</blockquote>
<h3 id="粘包-x2F-拆包处理"><a href="#粘包-x2F-拆包处理" class="headerlink" title="粘包&#x2F;拆包处理"></a>粘包&#x2F;拆包处理</h3><h4 id="什么是粘包-x2F-拆包"><a href="#什么是粘包-x2F-拆包" class="headerlink" title="什么是粘包&#x2F;拆包"></a>什么是粘包&#x2F;拆包</h4><blockquote>
<p>以下以TCP连接为例，因为UDP没有这个粘包&#x2F;拆包问题，还有就是UDP协议的使用比较少，常见的就是DNS协议了。</p>
<p>为什么会发生粘包与拆包问题呢？因为数据传输的传输层协议是TCP，这种协议是面向连接，可靠性高，底层使用字节流传输，这样就会引发一些问题？</p>
<p>如果客户端发送的数据太小，无法填满TCP连接缓冲区，TCP缓冲区就会等下一部分数据将其填满后，再一起发送给服务端，由于是一次性发送过来的，服务端就无法识别数据是客户端一次发过来的还是多次发过来的，这样的或就会照成粘包问题，就是多个数据包粘在一起了。</p>
<p>如果客户端一次发送的数据过大，超出了TCP缓冲区承载的能力，TCP就会先将满了的一部分数据发送给服务端，再发送接下来的，服务端没有一次性收到全部的数据，因此数据也是不完整的，就发生了拆包</p>
</blockquote>
<ul>
<li>正常图示</li>
</ul>
<p><img src="https://hexo-images-fei.oss-cn-hangzhou.aliyuncs.com/images/1694138905-image-20230908100825414.png" alt="image-20230908100825414"></p>
<ul>
<li>粘包图示</li>
</ul>
<p><img src="https://hexo-images-fei.oss-cn-hangzhou.aliyuncs.com/images/1694138942-image-20230908100901998.png" alt="image-20230908100901998"></p>
<ul>
<li>拆包图示</li>
</ul>
<p><img src="https://hexo-images-fei.oss-cn-hangzhou.aliyuncs.com/images/1694138971-image-20230908100931760.png" alt="image-20230908100931760"></p>
<ul>
<li>粘包&#x2F;拆包问题展示</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 客户端循环1000次向服务端发送数据</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">channelActive</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">1000</span>; i++) &#123;</span><br><span class="line">        ctx.channel().writeAndFlush(Unpooled.copiedBuffer(<span class="string">&quot;我是netty客户端&quot;</span>, CharsetUtil.UTF_8));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>运行结果</li>
</ul>
<p><img src="https://hexo-images-fei.oss-cn-hangzhou.aliyuncs.com/images/1694139945-image-20230908102545637.png" alt="image-20230908102545637"></p>
<p>我们发现，并没有我们想象中的服务端一个一个接收数据，而是多个数据内容粘连在一起了，这就是粘包，也与我发送的数据大小有关</p>
<h4 id="如何解决粘包拆包问题"><a href="#如何解决粘包拆包问题" class="headerlink" title="如何解决粘包拆包问题"></a>如何解决粘包拆包问题</h4><ul>
<li>指定数据包的长度，使用定长模式</li>
</ul>
<blockquote>
<p>意思是：如果你的数据包的长度是固定的，那么可以使用FixedLengthFrameDecoder定长解码器，设置数据包字节的长度，那么netty每次只会从入站缓冲区中取固定长度的数据，其它则等下一次获取。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 在处理器链的最前端添加此处理器链</span></span><br><span class="line"><span class="comment">// 设置每次接收20字节长度的数据</span></span><br><span class="line">addLast(<span class="keyword">new</span> <span class="title class_">FixedLengthFrameDecoder</span>(<span class="number">20</span>))</span><br></pre></td></tr></table></figure>

<ul>
<li>指定数据末尾分隔符</li>
</ul>
<blockquote>
<p>就是在数据包的结尾加上特定的分割符号示意，当入站处理器读取到这个分隔符的时候，就停止读取，下一次再进行读取。</p>
<p>分隔符解决拆包和粘包问题的，netty有两个解码器，分别是：LineBasedFrameDecoder和DelimiterBasedFrameDecoder。</p>
<p>**<code>LineBasedFrameDecoder</code>：**主要是按行符\n和回车符\t\n进行数据包拆分。</p>
<p>**<code>DelimiterBasedFrameDecoder</code>：**主要是按自定义符号进行数据拆分，比如按<code>$拆分，则在每条数据末尾加上$</code>。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 按换行进行拆分，8192指每次读取最大数据长度为8192字节</span></span><br><span class="line">addLast(<span class="keyword">new</span> <span class="title class_">LineBasedFrameDecoder</span>(<span class="number">8192</span>))</span><br><span class="line">    </span><br><span class="line"><span class="comment">// 按自定义符号拆分，比如按$符号</span></span><br><span class="line">addLast(<span class="keyword">new</span> <span class="title class_">DelimiterBasedFrameDecoder</span>(<span class="number">8192</span>, <span class="string">&quot;$&quot;</span>))</span><br></pre></td></tr></table></figure>

<ul>
<li>自定义编解码器</li>
</ul>
<blockquote>
<p>TODO 可以通过自定义编解码器，就是自定义数据结构来实现数据的拆分，解决粘包&#x2F;拆包问题。</p>
</blockquote>
<h3 id="自定义编解码器"><a href="#自定义编解码器" class="headerlink" title="自定义编解码器"></a>自定义编解码器</h3><h4><font color="red">TODO：自定义编解码器，未完待续...</font></h4></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://tengfei2233.gitee.io">Fei</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://tengfei2233.gitee.io/2023/11/21/netty%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8%EF%BC%8C%E5%9F%BA%E6%9C%AC%E5%8E%9F%E7%90%86%E5%88%86%E6%9E%90%EF%BC%8C%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3-%E6%9B%B4%E6%96%B0%E4%B8%AD/">https://tengfei2233.gitee.io/2023/11/21/netty%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8%EF%BC%8C%E5%9F%BA%E6%9C%AC%E5%8E%9F%E7%90%86%E5%88%86%E6%9E%90%EF%BC%8C%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3-%E6%9B%B4%E6%96%B0%E4%B8%AD/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://tengfei2233.gitee.io" target="_blank">飞の博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java/">Java</a><a class="post-meta__tags" href="/tags/SpringBoot/">SpringBoot</a><a class="post-meta__tags" href="/tags/netty/">netty</a><a class="post-meta__tags" href="/tags/Socket/">Socket</a></div><div class="post_share"><div class="social-share" data-image="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-11-10/netty-ai.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.staticfile.org/butterfly-extsrc/1.1.3/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.staticfile.org/butterfly-extsrc/1.1.3/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/wechat.png" target="_blank"><img class="post-qr-code-img" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/wechat.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/alipay.png" target="_blank"><img class="post-qr-code-img" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/alipay.png" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-full"><a href="/2023/11/10/%E5%9C%A8conda%E7%8E%AF%E5%A2%83%E4%B8%8B%E8%BF%90%E8%A1%8Cstable-diffusion-webui-AI%E7%BB%98%E5%9B%BE/" title="在conda环境下运行stable-diffusion-webui AI绘图"><img class="cover" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-11-10/ai.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">在conda环境下运行stable-diffusion-webui AI绘图</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2023/1/10/SpringBoot%E9%9B%86%E6%88%90Netty%E5%AE%9E%E7%8E%B0Socket%E9%80%9A%E4%BF%A1/" title="SpringBoot集成Netty实现Socket通信"><img class="cover" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-2-24/netty.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2023-01-10</div><div class="title">SpringBoot集成Netty实现Socket通信</div></div></a></div><div><a href="/2023/6/15/SpringBoot%E9%9B%86%E6%88%90SpringSecurity%E5%AE%9E%E7%8E%B0%E5%89%8D%E5%90%8E%E7%AB%AF%E5%88%86%E7%A6%BB%E6%9D%83%E9%99%90%E6%A0%A1%E9%AA%8C-%E6%96%B0%E7%89%88%E9%85%8D%E7%BD%AE%E6%96%B9%E5%BC%8F/" title="SpringBoot集成SpringSecurity实现前后端分离权限校验(新版配置方式)(待更新...)"><img class="cover" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-6-15/security.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2023-07-17</div><div class="title">SpringBoot集成SpringSecurity实现前后端分离权限校验(新版配置方式)(待更新...)</div></div></a></div><div><a href="/2023/6/15/Jackson%E8%A7%A3%E5%86%B3SpringMVC%E5%85%A8%E5%B1%80%E5%BA%8F%E5%88%97%E5%8C%96%E8%BF%94%E5%9B%9E%E4%B8%ADLong%E7%B1%BB%E5%9E%8B%E7%B2%BE%E5%BA%A6%E4%B8%A2%E5%A4%B1%E9%97%AE%E9%A2%98/" title="配置SpringMvc全局序列化与反序列化，解决Long类型下精度丢失问题（使用FastJson2）"><img class="cover" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-6-15/js.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2023-06-19</div><div class="title">配置SpringMvc全局序列化与反序列化，解决Long类型下精度丢失问题（使用FastJson2）</div></div></a></div><div><a href="/2023/2/27/SpringBoot%E9%9B%86%E6%88%90%E6%94%AF%E4%BB%98%E5%AE%9D%E6%B2%99%E7%AE%B1%E6%94%AF%E4%BB%98/" title="SpringBoot集成支付宝沙箱支付"><img class="cover" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-3-2/alipay.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2023-02-27</div><div class="title">SpringBoot集成支付宝沙箱支付</div></div></a></div><div><a href="/2023/2/12/SpringBoot%E9%9B%86%E6%88%90Redisson%E6%9B%BF%E6%8D%A2SpringCache%E5%BA%95%E5%B1%82%E5%AE%B9%E5%99%A8%E5%AE%9E%E7%8E%B0/" title="SpringBoot集成Redisson替换SpringCache底层容器实现"><img class="cover" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-2-26/redisson.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2023-02-12</div><div class="title">SpringBoot集成Redisson替换SpringCache底层容器实现</div></div></a></div><div><a href="/2023/2/10/SpringBoot%E9%9B%86%E6%88%90Redisson%E5%AE%9E%E7%8E%B0%E6%B3%A8%E8%A7%A3%E9%99%90%E6%B5%81/" title="SpringBoot集成Redisson实现注解限流"><img class="cover" src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-2-26/redisson.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2023-02-12</div><div class="title">SpringBoot集成Redisson实现注解限流</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/common/fei.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Fei</div><div class="author-info__description">当你想起来了，那就记录一点吧</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">24</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/tengfei2233"><i class="fab fa-github"></i><span>关注我</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/tengfei2233" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://gitee.com/tengfei2233" target="_blank" title="Gitee"><i class="fab fa-git"></i></a><a class="social-icon" href="/youfeige@outlook.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">当你迷茫的时候，那就静下心想想吧！</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#netty%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8%EF%BC%8C%E5%9F%BA%E6%9C%AC%E5%8E%9F%E7%90%86%E5%88%86%E6%9E%90%EF%BC%8C%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3-%E6%9B%B4%E6%96%B0%E4%B8%AD%E2%80%A6"><span class="toc-number">1.</span> <span class="toc-text">netty的基本使用，基本原理分析，相关问题解决(更新中…)</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#netty%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BB%8B%E7%BB%8D"><span class="toc-number">1.1.</span> <span class="toc-text">netty的基本介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFnetty"><span class="toc-number">1.1.1.</span> <span class="toc-text">什么是netty</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#netty%E4%B8%8Etomcat%E7%9A%84%E5%8C%BA%E5%88%AB%E6%98%AF%E4%BB%80%E4%B9%88"><span class="toc-number">1.1.2.</span> <span class="toc-text">netty与tomcat的区别是什么</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%9B%B8%E5%85%B3%E6%A6%82%E5%BF%B5-x2F-%E9%97%AE%E9%A2%98"><span class="toc-number">1.1.3.</span> <span class="toc-text">相关概念&#x2F;问题</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#netty%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8%EF%BC%88Socket%E8%BF%9E%E6%8E%A5%EF%BC%89"><span class="toc-number">1.2.</span> <span class="toc-text">netty的基本使用（Socket连接）</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#netty%E6%9C%8D%E5%8A%A1%E7%AB%AF"><span class="toc-number">1.2.1.</span> <span class="toc-text">netty服务端</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#netty%E5%AE%A2%E6%88%B7%E7%AB%AF"><span class="toc-number">1.2.2.</span> <span class="toc-text">netty客户端</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E4%BB%A3%E7%A0%81%E5%88%86%E6%9E%90"><span class="toc-number">1.3.</span> <span class="toc-text">基本代码分析</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%9C%8D%E5%8A%A1%E7%AB%AF"><span class="toc-number">1.3.1.</span> <span class="toc-text">服务端</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%A5%E7%AB%99%E5%A4%84%E7%90%86%E5%99%A8"><span class="toc-number">1.3.2.</span> <span class="toc-text">入站处理器</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%87%BA%E7%AB%99%E5%A4%84%E7%90%86%E5%99%A8"><span class="toc-number">1.3.3.</span> <span class="toc-text">出站处理器</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BF%83%E8%B7%B3%E6%A3%80%E6%B5%8B"><span class="toc-number">1.4.</span> <span class="toc-text">心跳检测</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%9C%8D%E5%8A%A1%E7%AB%AF%E5%A4%84%E7%90%86"><span class="toc-number">1.4.1.</span> <span class="toc-text">服务端处理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%A4%84%E7%90%86"><span class="toc-number">1.4.2.</span> <span class="toc-text">客户端处理</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%BF%9B%E9%98%B6"><span class="toc-number">1.4.3.</span> <span class="toc-text">进阶</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%B2%98%E5%8C%85-x2F-%E6%8B%86%E5%8C%85%E5%A4%84%E7%90%86"><span class="toc-number">1.5.</span> <span class="toc-text">粘包&#x2F;拆包处理</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E7%B2%98%E5%8C%85-x2F-%E6%8B%86%E5%8C%85"><span class="toc-number">1.5.1.</span> <span class="toc-text">什么是粘包&#x2F;拆包</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%A6%82%E4%BD%95%E8%A7%A3%E5%86%B3%E7%B2%98%E5%8C%85%E6%8B%86%E5%8C%85%E9%97%AE%E9%A2%98"><span class="toc-number">1.5.2.</span> <span class="toc-text">如何解决粘包拆包问题</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BC%96%E8%A7%A3%E7%A0%81%E5%99%A8"><span class="toc-number">1.6.</span> <span class="toc-text">自定义编解码器</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link"><span class="toc-number">1.6.1.</span> <span class="toc-text">TODO：自定义编解码器，未完待续...</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/11/21/netty%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8%EF%BC%8C%E5%9F%BA%E6%9C%AC%E5%8E%9F%E7%90%86%E5%88%86%E6%9E%90%EF%BC%8C%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3-%E6%9B%B4%E6%96%B0%E4%B8%AD/" title="netty的基本使用，基本原理分析，相关问题解(更新中...)"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-11-10/netty-ai.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="netty的基本使用，基本原理分析，相关问题解(更新中...)"/></a><div class="content"><a class="title" href="/2023/11/21/netty%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8%EF%BC%8C%E5%9F%BA%E6%9C%AC%E5%8E%9F%E7%90%86%E5%88%86%E6%9E%90%EF%BC%8C%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3-%E6%9B%B4%E6%96%B0%E4%B8%AD/" title="netty的基本使用，基本原理分析，相关问题解(更新中...)">netty的基本使用，基本原理分析，相关问题解(更新中...)</a><time datetime="2023-11-21T09:27:51.000Z" title="发表于 2023-11-21 17:27:51">2023-11-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/11/10/%E5%9C%A8conda%E7%8E%AF%E5%A2%83%E4%B8%8B%E8%BF%90%E8%A1%8Cstable-diffusion-webui-AI%E7%BB%98%E5%9B%BE/" title="在conda环境下运行stable-diffusion-webui AI绘图"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-11-10/ai.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="在conda环境下运行stable-diffusion-webui AI绘图"/></a><div class="content"><a class="title" href="/2023/11/10/%E5%9C%A8conda%E7%8E%AF%E5%A2%83%E4%B8%8B%E8%BF%90%E8%A1%8Cstable-diffusion-webui-AI%E7%BB%98%E5%9B%BE/" title="在conda环境下运行stable-diffusion-webui AI绘图">在conda环境下运行stable-diffusion-webui AI绘图</a><time datetime="2023-11-10T07:30:51.000Z" title="发表于 2023-11-10 15:30:51">2023-11-10</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/11/10/%E5%9C%A8Ubuntu20%E4%B8%8A%E5%AE%89%E8%A3%85CUDA-cuDNN-Miniconda%E7%8E%AF%E5%A2%83(%E5%85%B6%E5%AE%83%E7%B3%BB%E7%BB%9F%E5%90%8C%E7%90%86)/" title="在Ubuntu20上安装CUDA+cuDNN+Miniconda环境(其它系统同理)"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-11-10/ai.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="在Ubuntu20上安装CUDA+cuDNN+Miniconda环境(其它系统同理)"/></a><div class="content"><a class="title" href="/2023/11/10/%E5%9C%A8Ubuntu20%E4%B8%8A%E5%AE%89%E8%A3%85CUDA-cuDNN-Miniconda%E7%8E%AF%E5%A2%83(%E5%85%B6%E5%AE%83%E7%B3%BB%E7%BB%9F%E5%90%8C%E7%90%86)/" title="在Ubuntu20上安装CUDA+cuDNN+Miniconda环境(其它系统同理)">在Ubuntu20上安装CUDA+cuDNN+Miniconda环境(其它系统同理)</a><time datetime="2023-11-10T07:27:51.000Z" title="发表于 2023-11-10 15:27:51">2023-11-10</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/8/27/Docker-Compose%E5%AD%A6%E4%B9%A0/" title="Docker Compose学习"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-6-26/docker.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Docker Compose学习"/></a><div class="content"><a class="title" href="/2023/8/27/Docker-Compose%E5%AD%A6%E4%B9%A0/" title="Docker Compose学习">Docker Compose学习</a><time datetime="2023-08-27T15:34:50.000Z" title="发表于 2023-08-27 23:34:50">2023-08-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/8/27/Dockerfile%E5%AD%A6%E4%B9%A0/" title="Dockerfile学习"><img src="https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-6-26/docker.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Dockerfile学习"/></a><div class="content"><a class="title" href="/2023/8/27/Dockerfile%E5%AD%A6%E4%B9%A0/" title="Dockerfile学习">Dockerfile学习</a><time datetime="2023-08-27T15:34:37.000Z" title="发表于 2023-08-27 23:34:37">2023-08-27</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://blog-1306275892.cos.ap-shanghai.myqcloud.com/hexo/blogs/2023-11-10/netty-ai.png')"><div id="footer-wrap"><div class="copyright">&copy;2022 - 2024 By Fei</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">欢迎进入<a href="tengfei2233.gitee.io/">飞の博客</a>!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="https://cdn.staticfile.org/hexo-theme-butterfly/4.7.0/js/utils.min.js"></script><script src="https://cdn.staticfile.org/hexo-theme-butterfly/4.7.0/js/main.min.js"></script><script src="https://cdn.staticfile.org/hexo-theme-butterfly/4.7.0/js/tw_cn.min.js"></script><script src="https://cdn.staticfile.org/fancyapps-ui/4.0.31/fancybox.umd.min.js"></script><script src="https://cdn.staticfile.org/instant.page/5.1.1/instantpage.min.js" type="module"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.staticfile.org/pangu/4.0.7/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: '0kbeJfFlvhvkYfqMqwwVCx1a-gzGzoHsz',
      appKey: 'rziWUw1MTHMW7d9eeCQzu9HV',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.staticfile.org/valine/1.5.1/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><script defer="defer" id="ribbon" src="https://cdn.staticfile.org/butterfly-extsrc/1.1.3/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="https://cdn.staticfile.org/hexo-theme-butterfly/4.7.0/js/search/local-search.min.js"></script></div></body></html>